package com.ikangtai.shecare.common.db.sync;

import android.content.Context;

import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.DatabaseHelper;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncCompleteTaskMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.TasksUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

/**
 * Created on 2016/6/28.
 */
public class SyncCompleteTask {
    private Context context;
    private SyncCompleteTaskMsg syncCompleteTaskMsg;

    public SyncCompleteTask(Context context, SyncCompleteTaskMsg syncCompleteTaskMsg) {
        this.context = context;
        this.syncCompleteTaskMsg = syncCompleteTaskMsg;
        EventBus.getDefault().register(this);
    }

    public void syncCompleteTaskWithNetwork() {
        final DBManager dbManager = new DBManager(context);

        List<TasksUtil> completeTaskList = dbManager.getUnSyncedCompleteTask(App.userName);

        if (completeTaskList == null || completeTaskList.size() == 0) {
            EventBus.getDefault().post(syncCompleteTaskMsg);
        } else {
            try {
                String appendUrl = "task/addOrUpdateComplete.json";
                OKHttpUtil okHttpClient = new OKHttpUtil(context);
                JSONArray tasksListJsonArray = new JSONArray();

                for (int i = 0; i < completeTaskList.size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("taskID", completeTaskList.get(i).getTaskID());
                    jsonObject.put("taskType", 1);
                    jsonObject.put("completeDate", completeTaskList.get(i).getCompleteDate());
                    jsonObject.put("taskDelete", completeTaskList.get(i).getTaskDelete());
                    tasksListJsonArray.put(jsonObject);
                }

                okHttpClient.add("authToken", App.authToken);
                okHttpClient.add("comTasks", tasksListJsonArray);
                okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                    @Override
                    public void onFailure(Request request, IOException e) {
                        super.onFailure(request, e);
                        EventBus.getDefault().post(syncCompleteTaskMsg);
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        try {
                            JSONObject respJSONObj = new JSONObject(response.body().string());
                            int respCode = respJSONObj.getInt("code");

                            if (App.HTTP_RESP_OK == respCode) {
                                dbManager.updateDBSyncFlag(DatabaseHelper.COMPLETE_TASK_TABLE_NAME, App.userName);
                                AppLog.i("syncCompleteTaskWithNetwork onResponse success!");
                            } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                                OKHttpUtil.setNewToken();
                                syncCompleteTaskWithNetwork();
                            } else {
                                AppLog.i("insert task ids onResponse respCode failed! is:" + respCode);
                            }
                            if (respCode != App.HTTP_RESP_TOKEN_TIME_OUT)
                                EventBus.getDefault().post(syncCompleteTaskMsg);
                        } catch (JSONException e) {
                            AppLog.i("insert task ids onResponse failed!");
                            e.printStackTrace();
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
                EventBus.getDefault().post(syncCompleteTaskMsg);
            }

        }

    }
}
